<template>
<div class="task-manage">
    <div class="box-top">
        <el-form @submit.native.prevent class="form-between">
            <el-form-item label="任务名称">
                <el-input clearable placeholder="请输入任务名称" v-model="form.scheduleName"></el-input>
            </el-form-item>
            <el-form-item label="调度状态">
                <el-select clearable v-model="form.status" placeholder="请选择调度状态">
                    <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="调度周期">
                <el-select clearable v-model="form.periodType" placeholder="请选择调度周期">
                    <el-option v-for="item in periodList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="最近执行时间">
                <el-date-picker v-model="form.timeRange" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item style="margin-bottom:8px !important;" label="">
                <el-button type="primary" v-preventReClick="2000" @click="search">查询</el-button>
                <el-button v-preventReClick="2000" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="box-table">
        <el-table height="100%" v-loading="loading" :data="tableData" tooltip-effect="dark">
            <template slot="empty">
                <no-data :types="isSearch">
                    <span>暂无数据</span>
                </no-data>
            </template>
            <el-table-column prop="scheduleName" label="任务名称" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createOper" label="创建人" show-overflow-tooltip></el-table-column>
            <el-table-column prop="lastUpdateOper" label="修改人" show-overflow-tooltip></el-table-column>
            <el-table-column label="状态" show-overflow-tooltip>
                <template slot-scope="scope">{{scope.row.status?'已调度':'未调度'}}</template>
            </el-table-column>
            <el-table-column sortable prop="lastUpdateTime" label="最近修改时间" show-overflow-tooltip min-width="100"></el-table-column>
            <el-table-column sortable prop="lastExecTime" label="最近执行时间" show-overflow-tooltip min-width="100"></el-table-column>
            <el-table-column prop="period" label="调度周期" show-overflow-tooltip></el-table-column>
            <el-table-column prop="description" label="调度信息" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleDispatchEdit(scope.row)">编辑</el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-button type="text" @click="handleToDetail(scope.row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div v-if="tableData.length>0" class="box-pagenation">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
    <dispatch-set v-if="dispatchData.show" :dispatchData="dispatchData" @save="handleDispatch"></dispatch-set>
</div>
</template>

<script>
import {
    mapGetters,
    mapMutations
} from 'vuex'
import moment from 'moment'
import DispatchSet from '@/views/expEdit/dispatchSet'
import NoData from '@/components/NoData'
export default {
    name: 'TaskManage',
    components: {
        DispatchSet,
        NoData
    },
    data () {
        return {
            dispatchData: {
                show: false,
                title: '调度任务',
                form: {
                    cronObj: {},
                    periodType: 1,
                    schedulTime: '',
                    period: '',
                    moment: '',
                    status: 0,
                    time: [],
                    description: '',
                    scheduleName: '',
                    upstreamSchedules: [],
                    downstreamSchedules: []
                }
            },
            loading: false,
            statusList: [
                { value: 0, label: '已调度' },
                { value: 1, label: '未调度' }
            ],
            periodList: [
                { value: 0, label: '分钟' },
                { value: 1, label: '小时' },
                { value: 2, label: '天' },
                { value: 3, label: '周' },
                { value: 4, label: '月' }
            ],
            form: {
                scheduleName: '',
                status: '',
                periodType: '',
                timeRange: []
            },
            total: 0,
            pageSize: 10,
            currentPage: 1,
            tableData: [],
            isSearch: false
        }
    },
    created () {
        this.init()
    },
    computed: {
        ...mapGetters({
            projectId: 'common/getProjectId',
            experimentId: 'common/getExperimentId'
        })
    },
    methods: {
        ...mapMutations({
            setUpdateExp: 'common/setUpdateExp',
            setTypeId: 'common/setTypeId',
            setRemoveExp: 'common/setRemoveExp',
            setDispatchInfo: 'common/setDispatchInfo'
        }),
        handleDispatch () {
            let { cronObj, periodType, status, time, scheduleName, upstreamSchedules, downstreamSchedules, description } = this.dispatchData.form
            let params = {
                projectId: this.projectId,
                experimentId: this.experimentId,
                cronObj: JSON.stringify(cronObj),
                periodType,
                status,
                description,
                effDate: time[0] && moment(time[0]).format('YYYY-MM-DD HH:mm:ss'),
                endDate: time[1] && moment(time[1]).format('YYYY-MM-DD HH:mm:ss'),
                scheduleName,
                upstreamSchedules,
                downstreamSchedules
            }
            this.$post('/experiment/updateOfflineSchedule', params).then(res => {
                if (res.periodType) {
                    this.$message.success('保存成功')
                    this.dispatchData.show = false
                    this.init()
                }
            })
        },
        handleDispatchEdit (item) {
            let data = item
            let cronObj = JSON.parse(data.cronObj)
            let period = ''
            let moment = ''
            let schedulTime = ''
            switch (data.periodType) {
                case 5:
                    period = cronObj.monthExp
                    moment = cronObj.dayExp
                    schedulTime = new Date(`2019/5/5 ${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`)
                    break
                case 3:
                    period = cronObj.dayExp
                    schedulTime = new Date(`2019/5/5 ${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`)
                    break
                case 4:
                    period = 1
                    moment = cronObj.weekExp
                    schedulTime = new Date(`2019/5/5 ${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`)
                    break
                case 2:
                    period = cronObj.hourExp
                    schedulTime = new Date(`2019/5/5 ${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`)
                    break
                case 1:
                    period = cronObj.minuteExp
                    schedulTime = new Date(`2019/5/5 0:${cronObj.minuteExp}:${cronObj.secondExp}`)
                    break
            }
            this.dispatchData.form = {
                periodType: data.periodType,
                schedulTime,
                period,
                moment: +moment,
                cronObj,
                status: data.status,
                time: [new Date(data.effDate), new Date(data.endDate)],
                scheduleName: data.scheduleName,
                description: data.description,
                upstreamSchedules: data.upstreamSchedules,
                downstreamSchedules: data.downstreamSchedules
            }
            this.dispatchData.show = true
        },
        search () {
            this.currentPage = 1
            this.isSearch = true
            this.init()
        },
        init () {
            let { scheduleName, status, periodType, timeRange } = this.form
            this.loading = true
            let params = {
                projectId: this.projectId,
                experimentId: this.experimentId,
                scheduleName,
                status,
                periodType,
                lastExecTimeStart: timeRange[0] && moment(timeRange[0]).format('YYYY-MM-DD HH:MM:SS'),
                lastExecTimeEnd: timeRange[1] && moment(timeRange[1]).format('YYYY-MM-DD HH:MM:SS'),
                pageSize: this.pageSize,
                pageNum: this.currentPage
            }
            this.$post('/experiment/queryOfflineSchedules', params).then(res => {
                if (res && res.rows) {
                    this.getDispatchSchedule(this.tableData = res.rows)
                    this.total = res.rows.length
                }
            }).finally(() => {
                this.loading = false
            })
        },
        addZero (str) {
            if (str < 10) {
                return '0' + str
            }
            return str
        },
        // 获得调度周期
        getDispatchSchedule (arr) {
            for (let i = 0; i < arr.length; i++) {
                let cronObj = JSON.parse(arr[i].cronObj)
                let period = ''
                let schedulTimeStr = ''
                cronObj.hourExp = cronObj.hourExp ? this.addZero(cronObj.hourExp) : ''
                cronObj.minuteExp = cronObj.minuteExp ? this.addZero(cronObj.minuteExp) : ''
                cronObj.secondExp = cronObj.secondExp ? this.addZero(cronObj.secondExp) : ''
                switch (arr[i].periodType) {
                    case 5:
                        period = `${cronObj.monthExp}月`
                        schedulTimeStr = `每月${cronObj.dayExp}号,${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`
                        break
                    case 3:
                        period = `${cronObj.dayExp}天`
                        schedulTimeStr = `${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`
                        break
                    case 4:
                        period = '每周'
                        schedulTimeStr = `星期${cronObj.weekExp},${cronObj.hourExp}:${cronObj.minuteExp}:${cronObj.secondExp}`
                        break
                    case 2:
                        period = `${cronObj.hourExp}小时`
                        schedulTimeStr = `${cronObj.minuteExp}分${cronObj.secondExp}秒`
                        break
                    case 1:
                        period = `${cronObj.minuteExp}分钟`
                        schedulTimeStr = `${cronObj.secondExp}秒`
                        break
                }
                arr[i].period = period
                arr[i].schedulTimeStr = schedulTimeStr
            }
            return arr
        },
        reset () {
            this.keyword = ''
            this.isSearch = false
            this.currentPage = 1
            this.init()
        },
        handleToDetail (item) {
            item.experimentName = localStorage.getItem('experimentName')
            this.setDispatchInfo(item)
            this.$router.push('/taskDetail')
        },
        handleCurrentChange (val) {
            this.currentPage = val
            this.init()
        },
        handleSizeChange (val) {
            this.pageSize = val
            this.init()
        }
    }
}
</script>
<style lang="less">
    .task-manage {
        height: 100%;
        overflow: hidden;
        .box-table {
            height: calc(100% - 100px);
        }
    }
</style>
